package com.fc.test.compare;

import com.fc.test.compare.define.CompareInterface;
import com.fc.test.compare.define.CompareResult;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Liaopan on 2019/7/17.
 */
public class CompareColumnsReturnList implements CompareInterface {
    private static final Logger LOG = LoggerFactory.getLogger(CompareColumnsReturnList.class);

    DataSource source;
    DataSource target;

    private Class sourceClass;
    private Class targetClass;

    @Override
    public void init(DataSource sds, DataSource tds, Class sourceClass, Class targetClass) {
        this.source = sds;
        this.target = tds;
        this.sourceClass = sourceClass;
        this.targetClass = targetClass;
    }

    @Override
    public CompareResult compare(final String sourceQuery, final String targetQuery) throws Exception {
        QueryRunner sourceR = new QueryRunner(source, true);
        QueryRunner targetR = new QueryRunner(target, true);

        LOG.debug("====查询sql====");
        LOG.debug("source:" + sourceQuery);
        LOG.debug("target:" + targetQuery);
        LOG.debug("====end====");
        CompareResultList resultList = null;

        final CompareResultList.Builder builder = new CompareResultList.Builder();
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        final CountDownLatch latch = new CountDownLatch(2);

        cachedThreadPool.submit(() -> {
            try {
                builder.left(sourceR.query(sourceQuery, new ClassResultHandler(sourceClass)));
            } catch (Exception e) {
                LOG.error("原表查询出错！", e);
                builder.lMessage(e.getMessage());
            } finally {
                latch.countDown();
            }
        });

        cachedThreadPool.submit(() -> {
            try {
                builder.right(targetR.query(targetQuery, new ClassResultHandler(targetClass)));
            } catch (Exception e) {
                LOG.error("目标表查询出错！", e);
                builder.rMessage(e.getMessage());
            } finally {
                latch.countDown();
            }
        });

        latch.await();
        // 比对数据
        resultList = builder.builder();
        System.out.println("=====比对结果====");
        int lSize = Optional.ofNullable(resultList.getLeft()).map(List::size).orElse(-1);
        int rSize = Optional.ofNullable(resultList.getRight()).map(List::size).orElse(-1);
        System.out.println("源：" + lSize);
        System.out.println("目标：" + rSize);
        System.out.println("=================");

        return resultList;
    }
}
